package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.gdpu.base.PageView;
import org.gdpu.model.*;
import org.gdpu.service.SubjectService;
import org.gdpu.service.TestCategoryService;
import org.gdpu.service.TestPaperInfoService;
import org.gdpu.service.TestPaperService;
import org.gdpu.util.ChangeTime;
import org.gdpu.util.WordUtil;
import org.gdpu.vo.TestPaperVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-6-12
 * Time: 下午8:17
 * To change this template use File | Settings | File Templates.
 */
//生成word试卷
@Component("TestPaper")
@Scope("prototype")
public class TestPaperAction extends MyActionSupport implements ModelDriven<TestPaperVO> {

    @Qualifier("wordUtil")
    @Autowired
    private WordUtil wordUtil;

    private final static Logger logger = LogManager.getLogger(TestPaperAction.class);
    private HttpServletRequest request = ServletActionContext.getRequest();
    private Random random = new Random();
    private final TestPaperVO testPaperVO = new TestPaperVO();
    private TestCategoryService testCategoryService;
    private SubjectService subjectService;
    private TestPaperService testPaperService;
    private TestPaperInfoService testPaperInfoService;
    private TestPaperInfo testPaperInfo = new TestPaperInfo();
    private List<Test> tests = new ArrayList<Test>();
    private String testPaperId = ChangeTime.formatDate(ChangeTime.getCurrentDate());   //取试卷编号

    public String randomTestPaper() {

        String imgPath = "/img/";
        String saveImgPathDir = request.getSession().getServletContext().getRealPath(imgPath);
        // 得到备份文件的目录的真实路径
        String saveWordPathDirByTestPaper = "D:/CRM/_file/_testPaper/";
        File dir = new File(saveWordPathDirByTestPaper);
        String saveWordPathDirByTestPaperAnswer = "D:/CRM/_file/_testPaper/_answer/";
        File dirAnswer = new File(saveWordPathDirByTestPaperAnswer);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (!dirAnswer.exists()) {
            dirAnswer.mkdirs();
        }

        //考试科目
        //TODO:格式修改
        Subject subject = subjectService.findSubjectBySubjectName(testPaperVO.getSubject());
        if (subject == null) {
            testPaperVO.setResultMessage("请选择试卷对应的科目！谢谢合作！");
            return ERROR;
        }

        wordUtil = new WordUtil();
        WordUtil answerUtil = new WordUtil();
        wordUtil.setNum();
        answerUtil.setNum();
        saveTestPaperInfo();
        //输出试卷表头
        wordUtil.wordToTitle(subject.getSubjectName());
        answerUtil.wordToTitle(subject.getSubjectName());
        //输出试卷页眉
        wordUtil.setHeaderText(saveImgPathDir + "/schoolSign.jpg");
        answerUtil.setHeaderText(saveImgPathDir + "/schoolSign.jpg");
        //取各题型题目
        List<TestCategory> tcs = testCategoryService.allTestCategory();

        try {
            //输出选择题
            if (!testPaperVO.getChoiceNum().equals("")) {
                wordUtil.wordToSecondTitle(tcs.get(0).getType(), testPaperVO.getChoiceScore(), testPaperVO.getChoiceNum());
                answerUtil.wordToSecondTitle(tcs.get(0).getType(), testPaperVO.getChoiceScore(), testPaperVO.getChoiceNum());
                tests = testPaperService.findTestByCategory(tcs.get(0), subject);
                for (int i = 0; i < Integer.parseInt(testPaperVO.getChoiceNum()); i++) {
                    int flag = random.nextInt(tests.size());
                    saveTestPaper(testPaperVO.getChoiceScore(), flag);
                    wordUtil.wordToChoice(wordUtil.removeHTMLTag(tests.get(flag).getTheme()), i + 1);
                    answerUtil.wordToAnswerByChoiceOrJudge(tests.get(flag).getAnswer().getAnswer(), i + 1);
                    tests.remove(flag);
                    if (i == Integer.parseInt(testPaperVO.getChoiceNum()) - 1)
                        answerUtil.wordToLine();
                }
            }
        } catch (Exception e) {
            logger.error(e);
            testPaperVO.setResultMessage("生成试卷出错，请初始化试题类型或联系管理员!");
            testPaperService.delete(testPaperInfo);
            return ERROR;
        }

        //输出多选题
        if (!testPaperVO.getJudgeNum().equals("")) {
            wordUtil.wordToSecondTitle(tcs.get(1).getType(), testPaperVO.getMutiChoiceScore(), testPaperVO.getMutiChoiceNum());
            answerUtil.wordToSecondTitle(tcs.get(1).getType(), testPaperVO.getMutiChoiceScore(), testPaperVO.getMutiChoiceNum());
            tests = testPaperService.findTestByCategory(tcs.get(1), subject);
            for (int i = 0; i < Integer.parseInt(testPaperVO.getJudgeNum()); i++) {
                int flag = random.nextInt(tests.size());
                saveTestPaper(testPaperVO.getMutiChoiceScore(), flag);
                wordUtil.wordToChoice(wordUtil.removeHTMLTag(tests.get(flag).getTheme()), i + 1);
                answerUtil.wordToAnswerByChoiceOrJudge(tests.get(flag).getAnswer().getAnswer(), i + 1);
                tests.remove(flag);
            }
        }

        //输出判断题
        if (!testPaperVO.getJudgeNum().equals("")) {
            wordUtil.wordToSecondTitle(tcs.get(2).getType(), testPaperVO.getJudgeScore(), testPaperVO.getJudgeNum());
            answerUtil.wordToSecondTitle(tcs.get(2).getType(), testPaperVO.getJudgeScore(), testPaperVO.getJudgeNum());
            tests = testPaperService.findTestByCategory(tcs.get(2), subject);
            for (int i = 0; i < Integer.parseInt(testPaperVO.getJudgeNum()); i++) {
                int flag = random.nextInt(tests.size());
                saveTestPaper(testPaperVO.getJudgeScore(), flag);
                wordUtil.wordToInput(wordUtil.removeHTMLTag(tests.get(flag).getTheme()), i + 1);
                answerUtil.wordToAnswerByChoiceOrJudge(tests.get(flag).getAnswer().getAnswer(), i + 1);
                tests.remove(flag);
            }

        }
        //输出填空题
        if (!testPaperVO.getFillNum().equals("")) {
            wordUtil.wordToSecondTitle(tcs.get(3).getType(), testPaperVO.getFillScore(), testPaperVO.getFillNum());
            answerUtil.wordToSecondTitle(tcs.get(3).getType(), testPaperVO.getFillScore(), testPaperVO.getFillNum());
            tests = testPaperService.findTestByCategory(tcs.get(3), subject);
            for (int i = 0; i < Integer.parseInt(testPaperVO.getFillNum()); i++) {
                int flag = random.nextInt(tests.size());
                saveTestPaper(testPaperVO.getFillScore(), flag);
                wordUtil.wordToInput(tests.get(flag).getTheme(), i + 1);
                answerUtil.wordToAnswer(tests.get(flag).getAnswer().getAnswer(), i + 1);
                tests.remove(flag);
            }

        }
        //输出问答题
        if (!testPaperVO.getAskNum().equals("")) {
            wordUtil.wordToSecondTitle(tcs.get(4).getType(), testPaperVO.getAskScore(), testPaperVO.getAskNum());
            answerUtil.wordToSecondTitle(tcs.get(4).getType(), testPaperVO.getFillScore(), testPaperVO.getFillNum());
            tests = testPaperService.findTestByCategory(tcs.get(4), subject);
            for (int i = 0; i < Integer.parseInt(testPaperVO.getAskNum()); i++) {
                int flag = random.nextInt(tests.size());
                saveTestPaper(testPaperVO.getAskScore(), flag);
                wordUtil.wordToInput(wordUtil.removeHTMLTag(tests.get(flag).getTheme()), i + 1);
                answerUtil.wordToAnswer(wordUtil.removeHTMLTag(tests.get(flag).getAnswer().getAnswer()), i + 1);
                tests.remove(flag);
            }

        }

        testPaperId += testPaperVO.getOwner();
        wordUtil.saveWord(saveWordPathDirByTestPaper + testPaperId + ".doc");
        answerUtil.saveWordAnswer(saveWordPathDirByTestPaperAnswer + testPaperId + ".doc");
        /*wordUtil.wordConverter(saveFilePathDir + "/" + testPaperId + ".docx",
                saveFilePathDir + "/" + testPaperId + ".html",8);*/
        logger.trace("成功生成试卷！文件名为" + testPaperId);
        testPaperVO.setResultMessage("成功生成试卷！");
        return SUCCESS;
    }



    public String addTestPaper(){
        //TODO:转化word未完成
        /*转化word准备部分*/
   /*     String imgPath = "/img/";
        String saveImgPathDir = request.getSession().getServletContext().getRealPath(imgPath);
        // 得到备份文件的目录的真实路径
        String saveWordPathDirByTestPaper = "D:/CRM/_file/_testPaper/";
        File dir = new File(saveWordPathDirByTestPaper);
        String saveWordPathDirByTestPaperAnswer = "D:/CRM/_file/_testPaper/_answer/";
        File dirAnswer = new File(saveWordPathDirByTestPaperAnswer);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (!dirAnswer.exists()) {
            dirAnswer.mkdirs();
        }

        //考试科目
        Subject subject = subjectService.findSubjectBySubjectName(testPaperVO.getSubject());
        if (subject == null) {
            testPaperVO.setResultMessage("请选择试卷对应的科目！谢谢合作！");
            return ERROR;
        }
        wordUtil = new WordUtil();
        WordUtil answerUtil = new WordUtil();
        wordUtil.setNum();
        answerUtil.setNum();
        saveTestPaperInfo();
        //输出试卷表头
        wordUtil.wordToTitle(subject.getSubjectName());
        answerUtil.wordToTitle(subject.getSubjectName());
        //输出试卷页眉
        wordUtil.setHeaderText(saveImgPathDir + "/schoolSign.jpg");
        answerUtil.setHeaderText(saveImgPathDir + "/schoolSign.jpg");
        //取各题型题目
        List<TestCategory> tcs = testCategoryService.allTestCategory();*/
        /*转化word准备部分*/

        if("".equals(testPaperVO.getSumScore().trim())||"".equals(testPaperVO.getTestName().trim())
                ||"".equals(testPaperVO.getSubject().trim())||"".equals(testPaperVO.getTestIds())
                ||"".equals(testPaperVO.getTestScores())){
            testPaperVO.setResultMessage("添加试卷失败!");
            return ERROR;
        }else {
            saveTestPaperInfo();
            String [] testIds = testPaperVO.getTestIds().split(",");
            String [] testScores = testPaperVO.getTestScores().split(",");
            for(int i=0;i<testIds.length;i++){
                try {
                    int testId = Integer.parseInt(testIds[i]);
                    int testScore = Integer.parseInt(testScores[i]);
                    TestPaper testPaper = new TestPaper();
                    Test test = testPaperService.find(Test.class, testId);
                    testPaper.setTest(test);
                    testPaper.setScore(testScore);
                    testPaper.setDifficulty(0.0);
                    testPaper.setTestPaperInfo(testPaperInfo);
                    testPaperService.save(testPaper);

                } catch (NumberFormatException e) {
                    logger.catching(e);
                    testPaperInfoService.delete(testPaperInfo);
                    testPaperVO.setResultMessage("添加试卷异常,请重试!");
                    return ERROR;

                } catch (Exception e) {
                    logger.catching(e);
                    testPaperInfoService.delete(testPaperInfo);
                    testPaperVO.setResultMessage("添加试卷异常,请重试!");
                    return ERROR;

                }
            }
        }

        testPaperVO.setResultMessage("添加试卷成功");
        return SUCCESS;
    }



    private void saveTestPaperInfo() {
        testPaperInfo.setState(true);
        testPaperInfo.setSumScore(Float.parseFloat(testPaperVO.getSumScore()));
        testPaperInfo.setTestPaperId(testPaperId + testPaperVO.getOwner());
        testPaperInfo.setTestPaperName(testPaperVO.getTestName());
        testPaperInfo.setOwner(testPaperVO.getOwner());
        testPaperInfo.setSubject(subjectService.findSubjectBySubjectName(testPaperVO.getSubject()));
        testPaperInfo.setDescription(testPaperVO.getTestpaperDesc());
        testPaperService.save(testPaperInfo);
    }

    private void saveTestPaper(String score, int flag) {
        TestPaper testPaper = new TestPaper();
        testPaper.setDifficulty(0.0);
        testPaper.setTestPaperInfo(testPaperInfo);
        testPaper.setScore(Float.parseFloat(score));
        testPaper.setTest(tests.get(flag));
        testPaperService.save(testPaper);
    }

    public String showTestPaper() {
/*        List<TestPaperInfo> testPaperInfos = testPaperService.findAllTest();

        if (testPaperInfos == null) {
            testPaperVO.setResultMessage("还没生成试卷!");
            return ERROR;
        }
        for (TestPaperInfo t : testPaperInfos)
            t.setTestPaperId(t.getTestPaperId() + ".doc");

        testPaperVO.setTestPaperInfos(testPaperInfos);*/

        int maxResult = 10000;
        int firstIndex = 0;
        PageView<Test> pageView = new PageView<Test>(maxResult,1);
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("id", "desc");

        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();
        jpql.append(" and (o.owner = ?1 or o.state = 1)");
        params.add(testPaperVO.getAccount());


        pageView.setQueryResult(testPaperInfoService.getScrollData(TestPaperInfo.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(), orderBy));
        testPaperVO.setPageView(pageView);
        view = "/page/testPaper/showTestPaper.jsp";
        return VIEW;
    }

    public String showSingleTestPaper(){
        try {
            testPaperInfo = testPaperInfoService.find(TestPaperInfo.class,
                    Integer.parseInt(testPaperVO.getPaperId()));
        } catch (NumberFormatException e) {
            logger.catching(e);
            testPaperVO.setResultMessage("查看试卷异常,请重试!");
            return ERROR;
        }
        if("".equals(testPaperInfo.getTestPaperId())){
            testPaperVO.setResultMessage("试卷不存在,请重试!");
            return ERROR;
        }else {

            int maxResult = 10000;
            int firstIndex = 0;
            PageView<TestPaper> pageView = new PageView<TestPaper>(maxResult,1);
            // 按照条件排序
            LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
            orderBy.put("test.category.id", "asc");

            /** 列表条件 **/
            StringBuffer jpql = new StringBuffer("1=1");
            /** 列表条件的值 **/
            List<Object> params = new ArrayList<Object>();
            jpql.append(" and (o.testPaperInfo.id = ?1)");
            params.add(testPaperInfo.getId());

            pageView.setQueryResult(testPaperService.getScrollData(TestPaper.class, firstIndex, maxResult,
                    jpql.toString(),params.toArray(), orderBy));

            List<TestPaper> testPapers = pageView.getRecords();
            for(TestPaper testPaper : testPapers){
                Test test = testPaper.getTest();
                test.setTheme(test.getTheme().replaceAll("\\r\\n", "").replaceAll("\\t", "&nbsp;&nbsp;"));
                TestAnswer testAnswer = test.getAnswer();
                testAnswer.setAnswer(testAnswer.getAnswer().replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", "&nbsp;&nbsp;"));
                test.setAnswer(testAnswer);
                testPaper.setTest(test);
            }
            pageView.setRecords(testPapers);

            testPaperVO.setPageView(pageView);
            testPaperVO.setTestPaperInfo(testPaperInfo);
        }

        view = "/page/testPaper/singleTestPaper.jsp";
        return VIEW;
    }


    @Resource(name = "testPaperServiceImpl")
    public void setTestPaperService(TestPaperService testPaperService) {
        this.testPaperService = testPaperService;
    }

    @Resource(name = "testCategoryServiceImpl")
    public void setTestCategoryService(TestCategoryService testCategoryService) {
        this.testCategoryService = testCategoryService;
    }

    @Resource(name = "subjectServiceImpl")
    public void setSubjectService(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Resource(name = "testPaperInfoServiceImpl")
    public void setTestPaperInfoService(TestPaperInfoService testPaperInfoService) {
        this.testPaperInfoService = testPaperInfoService;
    }

    @Override
    public TestPaperVO getModel() {
        return testPaperVO;
    }
}
